package cn.softeem.tushu.utils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet(name = "BaseServlet")
public class BaseServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        Method processMethod = null;
        try {
            processMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("指定方法不存在");
        }
        try {
            String result = null;
            result = (String) processMethod.invoke(this, req, res);
            int pos = result.indexOf(':');
            String c = result.substring(0, 1);
            String path = result.substring(pos + 1);
            if (c.equals("f")) {
                req.getRequestDispatcher(path).forward(req, res);
            } else if (c.equals("s")) {
                res.sendRedirect(req.getContextPath() + path);
            } else if (c.equals("a")) {
                res.getWriter().print(path);
            } else if (c.equals("d")) {
                downPic(res, path);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }catch (NullPointerException e){

        }
    }

    private void downPic(HttpServletResponse res, String path) throws IOException {
        FileInputStream fis = new FileInputStream(path);
        ServletOutputStream os = res.getOutputStream();
        int len = -1;
        byte[] b = new byte[1024];
        while ((len = fis.read(b)) != -1) {
            os.write(b, 0, len);
        }
        os.flush();
        os.close();
        fis.close();
    }
}